package com.scut.campus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scut.campus.context.BaseContext;
import com.scut.campus.dto.LostDto;
import com.scut.campus.dto.LostUpdateDto;
import com.scut.campus.dto.PageDTO;
import com.scut.campus.entity.Lost;
import com.scut.campus.mapper.LostMapper;
import com.scut.campus.query.LostQuery;
import com.scut.campus.query.base.PageQuery;
import com.scut.campus.service.LostService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LostServiceImpl extends ServiceImpl<LostMapper, Lost> implements LostService {
    @Autowired
    private LostMapper lostMapper;

    @Override
    public void insertLost(LostDto lostDto) {
        Lost lost = new Lost();
        BeanUtils.copyProperties(lostDto, lost);
        lost.setUserId(BaseContext.getCurrentId());
        this.save(lost);
    }

    @Override
    public void updateLost(LostUpdateDto lostDto) {
        Lost lost = new Lost();
        BeanUtils.copyProperties(lostDto, lost);
        lost.setUserId(BaseContext.getCurrentId());
        this.updateById(lost);
    }

    @Override
    public PageDTO<Lost> queryMyLost(PageQuery pageQuery) {
        LambdaQueryWrapper<Lost> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(Lost::getUserId, BaseContext.getCurrentId());

        Page<Lost> page = pageQuery.toMpPageDefaultSortByCreateTimeDesc();
        page(page, lambdaQueryWrapper);
        return PageDTO.of(page, Lost.class);
    }

    @Override
    public PageDTO<Lost> listLost(LostQuery lostQuery) {
        Page<Lost> page = lostQuery.toMpPageDefaultSortByCreateTimeDesc();

        LambdaQueryWrapper<Lost> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .like(Strings.isNotBlank(lostQuery.getStr()), Lost::getDescription, lostQuery.getStr())
                .eq(lostQuery.getType() != null, Lost::getType, lostQuery.getType());


        page(page, lambdaQueryWrapper);
        return PageDTO.of(page, Lost.class);
    }

    @Override
    public Lost getOneById(Long lostId) {
        LambdaQueryWrapper<Lost> lambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Lost::getLostId, lostId);
        return this.getOne(lambdaQueryWrapper);
    }
}
